<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <h2>欢迎注册</h2>
        <p>加入我们，开启您的博客之旅</p>
      </div>
      <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-position="top" class="register-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" :prefix-icon="Message" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" :prefix-icon="Lock" placeholder="请输入密码"
                    show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" :prefix-icon="Lock" placeholder="请确认密码"
                    show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="register-button" @click="submitForm">注册</el-button>
        </el-form-item>
        <div class="login-link">
          已有账号？
          <el-link type="primary" @click="goToLogin">立即登录</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import {reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {User, Message, Lock} from '@element-plus/icons-vue'
import {saveUser, findUserByUsername, findUserByEmail} from '@/api/user'

export default {
  name: "RegisterView",
  setup() {
    const router = useRouter()
    const registerFormRef = ref(null)

    const registerForm = reactive({
      username: '',
      email: '',
      password: '',
      confirmPassword: ''
    })

    const validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else if (value.length < 3 || value.length > 20) {
        callback(new Error('长度在 3 到 20 个字符'))
      } else {
        findUserByUsername(value).then(res => {
          if (res.data) {
            callback(new Error('该用户名已被使用'))
          } else {
            callback()
          }
        }).catch(err => {
          console.error('API错误详情:', err.response || err)
          const errorMsg = err.response?.data?.message || '用户名验证服务不可用'
          callback(new Error(errorMsg))
        })
      }
    }

    const validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else {
        findUserByEmail(value).then(res => {
          if (res.data) {
            callback(new Error('该邮箱已被使用'))
          } else {
            callback()
          }
        }).catch(err => {
          console.error('API错误详情:', err.response || err)
          const errorMsg = err.response?.data?.message || '用户名验证服务不可用'
          callback(new Error(errorMsg))
        })
      }
    }

    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (registerForm.confirmPassword !== '') {
          registerFormRef.value.validateField('confirmPassword')
        }
        callback()
      }
    }

    const validatePassAgain = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }

    const rules = {
      username: [
        {required: true, message: '请输入用户名称', trigger: 'blur'},
        {validator: validateUsername, trigger: 'blur'}
      ],
      email: [
        {required: true, message: '请输入邮箱地址', trigger: 'blur'},
        {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']},
        {validator: validateEmail, trigger: 'blur'}
      ],
      password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 6, message: '密码长度不能小于6位', trigger: 'blur'},
        {validator: validatePass, trigger: 'blur'}
      ],
      confirmPassword: [
        {required: true, message: '请再次输入密码', trigger: 'blur'},
        {validator: validatePassAgain, trigger: 'blur'}
      ]
    }

    const submitForm = () => {
      registerFormRef.value.validate((valid) => {
        if (valid) {
          saveUser(registerForm).then(res => {
            ElMessage.success('注册成功！')
            router.push('/login')
          })
        } else {
          ElMessage.error('请正确填写表单！')
          return false
        }
      })
    }

    const goToLogin = () => {
      router.push('/login')
    }

    return {
      registerForm,
      registerFormRef,
      rules,
      submitForm,
      goToLogin,
      User,
      Message,
      Lock
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.register-box {
  width: 460px;
  padding: 40px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.register-header p {
  font-size: 16px;
  color: #909399;
}

.register-form {
  margin-top: 20px;
}

.register-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
  border-radius: 4px;
}

.login-link {
  margin-top: 15px;
  text-align: center;
  font-size: 14px;
  color: #606266;
}
</style>
